package com.igbeok.miscellaneous.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Test;

public class MainThread {

	@Test
	public void run1() {
		LiftOff lift = new LiftOff();
		lift.run();
	}

	@Test
	public void basicThread() {
		Thread thread = new Thread(new LiftOff());
		thread.start();
		System.out.println("Waiting for Lift Off");
	}

	/*
	 * public void basicThread2(){ Thread thread = new Thread(new
	 * TaskWithResult(0)); //该构造函数未定义 }
	 */

	@Test
	public void moreBasicThread() {
		for (int i = 0; i < 5; i++) {
			new Thread(new LiftOff()).start();
		}
		System.out.println("Waiting for Lift Off");
	}

	@Test
	public void exercise1() {
		for (int i = 0; i < 5; i++) {
			new Thread(new Exercise1()).start();
		}
		System.out.println("Waiting for Exercise1");
	}

	@Test
	public void cachedThreadPool() {
		ExecutorService service = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			service.execute(new LiftOff());
		}
		service.shutdown();
	}

	@Test
	public void fixedThreadPool() {
		ExecutorService service = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 5; i++) {
			service.execute(new LiftOff());
		}
		service.shutdown();
	}

	@Test
	public void singleThreadExecutor() {
		ExecutorService service = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 5; i++) {
			service.execute(new LiftOff());
		}
		service.shutdown();
	}

	@Test
	public void callableThreadTest() {
		ExecutorService service = Executors.newCachedThreadPool();
		List<Future<String>> results = new ArrayList<Future<String>>();
		for (int i = 0; i < 5; i++) {
			results.add(service.submit(new TaskWithResult(i)));
		}

		for (Future<String> fs : results) {
			try {
				System.out.println(fs.get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Test
	public void sleepingThreadTest() {
		ExecutorService service = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			service.execute(new SleepingTask());
		}
	}

	@Test
	public void execise11Test() {
		Execise11 execise11 = new Execise11();
		ExecutorService service = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			service.execute(new Execise11Task(execise11));
		}
		service.shutdown();
	}
}
